const { Nuxt, Builder } = require("nuxt");
const Koa = require("koa");
const path = require("path");
const pkg = require("./package.json");
const gogs = require("./gogs");
const _ = require("lodash");
const ding = require("./ding");
const isDev = (process.env.NODE_ENV || "dev") === "dev";
const port = pkg.config.nuxt.port || 3000;
const host = pkg.config.nuxt.host || "0.0.0.0";

const app = new Koa();

// 用指定的配置对象实例化 Nuxt.js
const config = require("./nuxt.config.js");
const nuxt = new Nuxt(Object.assign(config, { dev: isDev }));

// 在开发模式下启用编译构建和热加载
if (isDev) {
    const builder = new Builder(nuxt);
    builder.build();
}

// error
app.use(async (ctx, next) => {
    ctx.set("X-Powered-By", "qingful");

    try {
        await next();
    } catch (err) {
        throw err;
    }
});

// gogs
app.use(gogs);

// 用 Nuxt.js 渲染每个路由
app.use(async (ctx, next) => {
    await next();
    ctx.status = 200; // koa defaults to 404 when it sees that status is unset
    return new Promise((resolve, reject) => {
        ctx.res.on("close", resolve);
        ctx.res.on("finish", resolve);
        nuxt.render(ctx.req, ctx.res, promise => {
            // nuxt.render passes a rejected promise into callback on error.
            promise.then(resolve).catch(reject);
        });
    });
});

// 钉钉
ding("系统提示", "应用启动成功");

// 服务端监听
app.listen(port, host);
console.log("Server listening on http://" + host + ":" + port);
